package com.yc.wxcontroller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yc.common.secure.support.SecureAuthenticationProvider;
import com.yc.common.utils.HttpsUtils;
import com.yc.entity.Attendance;
import com.yc.entity.User;
import com.yc.entity.WxUser;
import com.yc.mapper.AttendanceMapper;
import com.yc.mapper.SchoolYearMapper;
import com.yc.mapper.UserMapper;
import com.yc.service.ClassInfoService;
import com.yc.service.UserService;
import com.yc.service.impl.MajorInfoServiceImpl;
import com.yc.service.impl.StudentInfoServiceImpl;
import com.yc.service.impl.WxUserServiceImpl;
import com.yc.vo.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author mqm
 * @version 1.0
 * @date 2023/7/5 11:52
 */
@RestController
public class WxUserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private WxUserServiceImpl wxUserService;
    @Resource
    private StudentInfoServiceImpl studentInfoService;
    @Resource
    private SchoolYearMapper schoolYearMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private AttendanceMapper attendanceMapper;
    @Resource
    private MajorInfoServiceImpl majorInfoService;
    @Autowired
    private ClassInfoService classInfoService;


    @ApiOperation("微信用户授权登录")
    @PostMapping("/wxlogin")
    public Result WxLogin(@RequestParam(value = "Appid") String Appid, @RequestParam(value = "code", required = false) String code, @RequestParam(value = "avatarUrl") String avatarUrl,
                          @RequestParam(value = "nickname") String nickname, @RequestParam("username") String username, @RequestParam("session_key") String session_key, @RequestParam("openID") String openID) {
        Result result = wxUserService.WxLogin(Appid, code, avatarUrl, nickname, username, session_key, openID);
        return result;
    }

    @ApiOperation("根据工号查询")
    @PostMapping("wx/queryMan")
    public Result queryMan(@RequestParam("username") String username) {
        Map<String, Object> map = userService.queryMan(username);
        return Result.success(map);
    }

    @ApiOperation("用于验证时候已经登录，如已经执行该方法说明已经存在")
    @PostMapping("wx/querysession")
    public Result querysession_key(@RequestParam("code") String code, @RequestParam("username") String username) {
        int b = wxUserService.contrastopenID(code, username);
        if (b==1) {
            Object session_key = redisTemplate.opsForHash().get("WXSESSIONKEY::" + username, "session_key");
            redisTemplate.expire("WXSESSIONKEY::" + username, 66, TimeUnit.HOURS);
            return Result.success(session_key);
        } else if (b==2){
            return Result.error(2,"请登录");
        } else {
            return Result.error(-1, "该微信号已绑定账号");
        }
    }

    /**
     * 每次登录刷新时间   66小时
     */
    @ApiOperation("刷新登录时间")
    @PostMapping("wx/addTime")
    public void addredisTime(@RequestParam("username") String username){
        redisTemplate.expire("WXSESSIONKEY::"+username,66,TimeUnit.HOURS);
    }

    @ApiOperation("放行了此次查询，验证登录时间是否失效")
    @PostMapping("wx/queryTime")
    public Result queryRedisTime(@RequestParam("username") String username) {
        Long wxlogin = redisTemplate.getExpire("WXSESSIONKEY::" + username);
        if (wxlogin < 0) {
            return Result.error(0, "会话失效");
        } else {
            return Result.error(1, "通过");
        }
    }

    @ApiOperation("查找是否是默认密码")
    @PostMapping("wx/queryPwd")
    public Result queryPwd(@RequestParam("stuid") String stuid) {
        Result result = null;
        if (stuid.length() == 11) {
            result = studentInfoService.queryPwd(stuid);
        } else if (stuid.length() == 10 && SecureAuthenticationProvider.status) {
            result = studentInfoService.queryPwd(stuid);
        }else if(stuid.matches("[a-zA-Z0-9]+")){
            result = wxUserService.queryPwd(stuid);
        }else if (stuid.length() == 10) {
            result = wxUserService.queryPwd(stuid);
        } else {
            result = Result.error("系统异常,联系管理员");
        }
        return result;
    }

    @ApiOperation("判断微信号是否绑定")
    @PostMapping("wx/queryOpenID")
    public Result queryOpenid(@RequestParam("code") String code) {
        Result result = wxUserService.queryOpenId(code);
        return result;
    }

    @ApiOperation("学生修改密码")
    @PostMapping("wx/updatePwdBystu")
    public Result updatePwdByStu(@RequestParam("stuid") String stuid, @RequestParam("pwd") String pwd) {
        studentInfoService.updatePwdByStu(stuid, pwd);
        return Result.success("修改成功，请重新登录!");
    }

    @ApiOperation("学生判断与原密码一致")
    @PostMapping("wx/querystupwd")
    public Result querystupwd(@RequestParam("stuid") String stuid, @RequestParam("pwd") String pwd) {
        Result result = studentInfoService.querypwdstu(stuid, pwd);
        return result;
    }

    @ApiOperation("教师判断是否与原密码一致")
    @PostMapping("wx/queryPwdBysys")
    public Result queryPwdBysys(@RequestParam("username") String username, @RequestParam("pwd") String pwd) {
        Result result = wxUserService.queryPwdBysys(username, pwd);
        return result;
    }

    @ApiOperation("教师修改密码")
    @PostMapping("wx/updatePwdBysys")
    public Result updatePwdBysys(@RequestParam("username") String username, @RequestParam("pwd") String pwd) {
        Result result = wxUserService.updatePwdBysys(username, pwd);
        return result;
    }

    @ApiOperation("登录首页的微信授权登录")
    @PostMapping("wx/wxloginagain")
    public Result wxloginagain(@RequestParam("code") String code, @RequestParam("username") String username) {
        Result result = wxUserService.wxloginagain(code);
        return result;
    }

    /**
     * @Description 查询当前月份特定老师考过勤的数量
     * @Return
     * @Author dm
     * @Date Created in 2023/7/26 18:50
     **/
    @ApiOperation("查询当前月份特定老师考过勤的数量")
    @GetMapping("wx/queryCurCourNums")
    public Long queryCurCourNums(String username) {
        //先查询出来老师的id
        Integer id = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username)).getId();
        Long count = attendanceMapper.selectCount(Wrappers.<Attendance>lambdaQuery().eq(Attendance::getTeacherid, id));
        return count;
    }

    /**
     * @Description 查询历史考勤记录
     * @Return
     * @Author dm
     * @Date Created in 2023/7/28 0:49
     **/
    @ApiOperation("查询历史考勤记录")
    @GetMapping("wx/queryHistories")
    public Result queryHistories(String username, String year, String week) {
        //先将所有的年月日查询出来
        List<String> xries = schoolYearMapper.queryXries(year, week);
        Result result = wxUserService.queryHistories(username, xries);
        return result;
    }

    /**
     * @Description 查询特定老师本月以及本周的考勤次数
     * @Return
     * @Author dm
     * @Date Created in 2023/8/1 11:50
     **/
    @ApiOperation("查询历史考勤记录")
    @GetMapping("wx/queryHistoriesNums")
    public Result queryNums(String username) {
        int tid = userMapper.selectOne(Wrappers.<User>lambdaQuery().
                eq(User::getUsername, username)).getId();
        //先得到本月的年以及月份
        Date date=new Date();//此时date为当前的时间
        SimpleDateFormat dateFormat=new SimpleDateFormat("YYYY-MM");//设置当前时间的格式，为年-月-日
        //先查询本月的考勤记录
        Integer yearNums = userMapper.queryHitMonth(tid + "", dateFormat.format(date));
        //在查询本周的考勤次数
        dateFormat = new SimpleDateFormat("YYYY-MM-dd");
        List<String> otherDatesInSameWeek = HttpsUtils.getOtherDatesInSameWeek(dateFormat.format(date));
        Integer weekNums = userMapper.queryHisWeek(tid + "", otherDatesInSameWeek);
        Map<String, Integer> hisNums = new HashMap<>();
        hisNums.put("yearNums", yearNums);
        hisNums.put("weekNums", weekNums);
        return Result.success(hisNums);
    }

//-------------------------------------------------------------------------------------------
    /**
     *
     * @param school_year
     * @param mname
     * @param yearnumber
     * @param cname
     * @return
     */
    @ApiOperation("直接查出教师一年的课程数")
    @PostMapping("wx/selectByteaYear")
    public Result selectByteaYear( @RequestParam("school_year") String school_year,@RequestParam("mname") String mname,@RequestParam("yearnumber") String yearnumber,@RequestParam("cname") String cname){
        List<Map<String, Object>> maps = userService.selectByteaYearBywx(school_year,mname,yearnumber,cname);
        return Result.success(maps);
    }

    /**
     * 测试 ，到时候要调用的，前端写的是死的
     * @param nowdays
     * @return
     */
    @ApiOperation("查询今天对应的学期")
    @PostMapping("wx/queryNowdays")
    public Result queryNowTerm(@RequestParam("nowdays") String nowdays){
        String nowTerm = userService.queryNowTerm(nowdays);
        return Result.success(nowTerm);
    }

    /**
     * 根据实际情况改的        测试是50         上线一定要改
     * @return
     */
    @ApiOperation("查询学生分数比较低的")
    @PostMapping("wx/queryfail")
    public Result selectScore(){
        List<Map<String, Object>> queryfail = userService.queryfail();
        return Result.success(queryfail);
    }

    @ApiOperation("查找分数占比")
    @PostMapping("wx/selectproportion")
    public Result selectproportion( @RequestParam("cname") String cname){
        Map<String, Object> selectproportion = userService.selectproportion(cname);
        return Result.success(selectproportion);
    }

    @ApiOperation("查专业的所有班级低于35人")
    @PostMapping("wx/selectBnameAndCname")
    public Result selectBnameAndCname(@RequestParam("mname") String mname){
        List<Map<String, Object>> lists = userService.selectBnameAndCname(mname);
        return Result.success(lists);
    }

    @ApiOperation("查询考勤统计")
    @PostMapping("wx/selectBystuSum")
    public Result selectBystuSum( @RequestParam("pageSize") int pageSize,@RequestParam("pageNum") int pageNum,@RequestParam("majorName") String stuid){
        Map<String, Object> map = studentInfoService.selectBystuSum( stuid);
        return Result.success(map);
    }

    @ApiOperation("专业年份变化查询班级")
    @PostMapping("wx/selectClass")
    public Result selectClass(@RequestParam("mname") String mname, @RequestParam("yearnumber") String year){
        List<String> list = majorInfoService.selectClass(mname, year);
        return Result.success(list);
    }

    @ApiOperation("查询专业名")
    @PostMapping("wx/queryMname")
    public Result queryMname(){
        List<String> list = majorInfoService.queryMname();
        return Result.success(list);
    }

    @ApiOperation("查年级")
    @PostMapping("wx/queryYearnumber")
    public Result queryYearnumber(){
        List<String> list = classInfoService.queryYearnumber();
        List<String> filteredList = list.stream()
                .filter(s -> s != null && !s.isEmpty())
                .collect(Collectors.toList());
        return Result.success(filteredList);
    }

    @ApiOperation("查询所有学期")
    @PostMapping("wx/queryTerms")
    public Result queryTerms(){
        List<String> list = wxUserService.queryTerms();
        return Result.success(list);
    }

    @ApiOperation("小程序查询今天对应的学期")
    @PostMapping("wx/queryTerm")
    public Result queryTerm( @RequestParam("time") String time){
        Map<String, Object> map = wxUserService.queryTerm(time);
        return Result.success(map);
    }

    @ApiOperation("小程序查学生考勤分数根据班级")
    @PostMapping("wx/selectByCname")
    public Result selectByCname(@RequestParam("cname") String cname){
        List<Map<String, Object>> maps = wxUserService.selectByCname(cname);
        return Result.success(maps);
    }

    @ApiOperation("查专业和班级")
    @PostMapping("wx/selectBanji")
    public Result selectBanji(){
        List<Map<String, Object>> maps = classInfoService.selectBanji();
        return Result.success(maps);
    }

}
